#!/usr/bin/python3
# 从miranda的结果中提取需要的结果
import sys
import os
import re
import fileinput
import multiprocessing
import datetime
from File import FileWriter


def about():
    print('\t\t\t\t\t本脚本')
    print('\t用来从miranda的输出结果中提取需要的配对结果')
    print('\t输出文件为.miranda结尾的utf-8编码文本文件\n')
    print('\t##########\t文档说明\t##########')
    print('\t-i：要输入的的文件，多个文件以逗号分隔')
    print('\t-o：要输出的文件或文件夹，若为文件，多个文件以逗号分隔')
    print('\t\t若-o参数为空，默认使用相应输入文件的文件名')
    print('\t\t若-o参数为目录，默认使用相应输入文件的文件名')
    print('\t-p：要使用的进程数')
    exit()


class extract(multiprocessing.Process):                 # 继承定义的进程类
    def __init__(self, inputFile, outputFile, label):
        multiprocessing.Process.__init__(self)
        self.inputFile = inputFile
        self.outputFile = outputFile
        self.label = label

    def run(self):
        outputFile = self.outputFile
        inputFile = self.inputFile
        label = self.label
        pattern = re.compile('^>>')
        print("进程" + str(label) + " --- 输入文件:" + str(inputFile) + "\t\t输出文件:" + str(outputFile))
        if not os.path.isfile(outputFile):
           w = open(outputFile, 'x')
           w.close()
        else:
            with FileWriter(outputFile) as w:
                with fileinput.input(inputFile) as f:
                    for line in f:
                        if pattern.match(line):
                            # print(line)
                            line = line.strip('\n')
                            lines = re.split("\\s+", line)
                            lines[0] = re.sub(r'>>', '', lines[0])
                            w.write(lines[0] + "\t" + lines[1] + '\n')


def splitFiles(inputFile, thread):
    results = []
    if thread > len(inputFile):
        return splitFiles(inputFile, len(inputFile))
    else:
        if thread > 1 and thread >= len(inputFile):
            size = len(inputFile) // thread             # 每进程需要处理多少文件
            for i in range(thread):
                if i < thread - 1:
                    results.append(inputFile[i * size: size * (i + 1)])
                else:
                    results.append(inputFile[i * size: ])
        else:
            results.append(inputFile)
        return results


def extract_miranda(inputFile, outputFile, thread):
    begin = datetime.datetime.now()
    print("程序开始于：%s" % begin)

    if inputFile:  # 判断一下输入的文件数量，分割一下，把文件处理好
        inputFile = re.split(r',', inputFile)
        for file in iter(inputFile):
            if not os.path.isfile(file):
                print(file + "不是文件")
                exit()
    else:
        print("没有任何输入文件")
        exit()

    realRun = []
    inputFile = splitFiles(inputFile, thread)
    outputDir = None
    i = 1
    if outputFile:  # 先检查一下是否需要制定输出目录
        outputFile = re.split(r',', outputFile)

        for inFile, outFile in zip(inputFile, outputFile):
            realRun.append(extract(inputFile=inFile, outputFile=outFile, label=i))
            i += 1
    else:
        for files in iter(inputFile):
            for file in iter(files):
                outFile = re.sub('\..*', '.miranda', file)
                realRun.append(extract(inputFile=file, outputFile=outFile, label=i))
                i += 1


    for process in iter(realRun):
        process.start()

    for process in iter(realRun):
        process.join()

    end = datetime.datetime.now()
    print("程序终止于：%s" % end)
    print("一共花费：%s" % str(end - begin))


if __name__ == '__main__':
    parameters = {}  # 用来读取命令行参数的，遍历所有参数，开头以-开始的，下一个就作为参数附加，然后统一添加到一个词典中，再提取出来
    if len(sys.argv) <= 1:
        about()
    try:
        for i in range(len(sys.argv)):
            if sys.argv[i] == '-h' or sys.argv[i] == '--help':
                about()
            if sys.argv[i].startswith('-'):
                parameters.update({sys.argv[i]: sys.argv[i + 1]})
            elif sys.argv[i].startswith('--'):
                parameters.update({sys.argv[i]: sys.argv[i + 1]})
    except IndexError:  # 判断参数是否输入有误
        print("输入的参数有误")
        exit()

    inputFile = parameters.get('-i')  # 提取所有的输入文件

    outputFile = parameters.get('-o')                   # 提取所有的输出文件

    if not parameters.get('-p'):
        thread = 1
    else:
        try:

            thread = int(parameters.get('-p'))
            if thread < 1:  # thread 如果没有设置之类的，默认为1
                thread = 1
        except ValueError:
            print("-p参数需要输入整数")

    extract_miranda(inputFile=inputFile, outputFile=outputFile, thread=thread)
    input("任意键退出")
